package com.metaera.app.controller.presenter;

import com.metaera.app.controller.core.RequestPresenter;
import com.metaera.app.controller.view.core.INetworkRequestView;
import com.metaera.app.data.DataRepository;
import com.metaera.app.data.model.PhoneCodeResponse;
import com.metaera.app.data.rx.ResponseObserver;
import com.metaera.app.data.rx.SchedulersTransformer;

import java.util.ArrayList;
import java.util.List;

public class PhoneCodePresenter extends RequestPresenter<INetworkRequestView<List<PhoneCodeResponse>>> {

    private List<PhoneCodeResponse> data;

    public void execute() {
        DataRepository.getInstance()
                .getPhoneCode()
                .compose(SchedulersTransformer.transformer())
                .subscribe(new ResponseObserver<>(
                                this,
                                mView,
                                response -> {
                                    data = response.getData();
                                    mView.successful(data);
                                }
                        )
                );
    }

    public void search(CharSequence keyword) {
        if (data == null) {
            return;
        }

        if (keyword == null || keyword.length() == 0) {
            mView.successful(data);
            return;
        }

        List<PhoneCodeResponse> result = new ArrayList<>();
        for (PhoneCodeResponse code : data) {
            if (code.getCountry().contains(keyword.toString())) {
                result.add(code);
            }
        }

        mView.successful(result);
    }
}
